var canvasElement = document.getElementById("track");
var track = canvasElement.getContext("2d");
track.clearRect(0, 0, track.canvas.width, track.canvas.height);

var img = new Image();
var img2 = new Image();

img.src='../static/images/car1.png';
img2.src='../static/images/car2.png';
var y=700;
var z=700;

img.onload = function () {

    track.drawImage(img, 160, y, 79, 182);

    setInterval(function () {
        get_position();
    	z-=15;
        track.save();
        track.clearRect(0, 0, track.canvas.width, track.canvas.height);
        //track.rotate(Math.PI / 180 * (angle -= 10)); //rotating at 10 degrees interval..
        track.drawImage(img, 160, y,79,182);
        track.translate(160, y);
        track.drawImage(img2, 160, z);
        track.translate(160, z);
        track.restore();
        if(y<-450) y=700;
        if(z<-450) z=700;
    }, 60);
}

var get_position=function(){
    $.ajax('/get_pos', {
        type: 'get',
        cache:false,
        dataType: 'json',
        success: function (res) {
            if (res.error) {
                alert("Error en la peticion " + error);
            }
            y=res.response.position;
            console.log(y)
        }
    });
}